package com.ly.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ly.component.threadpool.httpclient.WSXYHttpClient;
import com.ly.model.form.CaptchaForm;
import com.ly.utils.MyJsonUtil;
import com.ly.utils.MyMapUtil;
import com.ly.utils.MyStringUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class CaptchaService {
	private WSXYHttpClient httpClient;

	public CaptchaService() {
		httpClient = new WSXYHttpClient();
	}

	public void stop() {
		httpClient.close();
	}

	public String getCaptchaByHuman(BufferedImage captchaImg) {
		File file = new File(String.format("%s.png", MyStringUtil.randomID()));
		try {
			ImageIO.write(captchaImg, "png", file);
			if (Desktop.isDesktopSupported()) {
				Desktop.getDesktop().open(file);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		Scanner sc = new Scanner(System.in);
		String captchaCode = sc.next();
		file.delete();
		return captchaCode;
	}

	public String getCaptchaByServer(BufferedImage captchaImg, String captchaServer) {
		if (captchaServer == null) {
			return null;
		}
		try {
			String img = base64Convert(captchaImg);
			CaptchaForm captchaForm = new CaptchaForm();
			captchaForm.setImg(img);
			String captchaPath = String.format("http://%s/api/tr-run/", captchaServer);
			String parseString = httpClient.doPost(captchaPath, captchaForm);
			if (parseString == null) {
				return null;
			}
			Map<String, Object> parseMap = MyJsonUtil.string2Obj(parseString, new TypeReference<Map<String, Object>>() {
			});
			if (parseMap != null) {
				int statusCode = MyMapUtil.get(parseMap, "code");
				if (statusCode == 200) {
					List<?> raw = MyMapUtil.mapNode(parseMap, "data/raw_out[0]");
					String captchaCode = (String) raw.get(1);
					System.out.println("识别的验证码为: " + captchaCode);
					return captchaCode;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String base64Convert(BufferedImage image) {
		try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
			ImageIO.write(image, "png", bos);
			return Base64.getEncoder().encodeToString(bos.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
